<template>
  <div class="app-container flex flex-sub" style="background: none; height: 100%; padding: 1rem">
    <div class="flex" style="width: 380px; height: 100%">
      <el-card shadow="never" class="box-card flex-sub" style="overflow: auto">
        <div>
          <el-button size="small" type="primary" @click="toAdd({ guid: '' }, 'addEmpty')">
            <i class="iconfont icon-xinzenghuizong" style="font-size: 13px; margin-right: 5px" />新增网格
          </el-button>
        </div>

        <div style="border: 1px solid #c8c8c8; padding: 0.7rem; margin-top: 1rem">
          <div class="flex" style="margin-bottom: 1rem; justify-content: space-between">
            <el-button size="small" @click="toExpandAll('是')">
              <i class="el-icon-plus" style="color: #606266" />
              <span style="color: #606266">全部展开</span>
            </el-button>

            <el-button size="small" @click="toExpandAll('否')">
              <i class="el-icon-minus" style="color: #606266" />
              <span style="color: #606266">全部收起</span>
            </el-button>

            <el-button size="small" @click="toRefreshGridTree">
              <i class="el-icon-refresh" style="color: #606266" />
              <span style="color: #606266">刷新</span>
            </el-button>
          </div>
          <el-input v-model="gridName" style="margin-bottom: 1rem" placeholder="请输入网格名称" prefix-icon="el-icon-search"
            class="filter-item search-item" @keyup.native="toSearchGridTree" />

          <div style="margin-right: 0px; overflow: auto" :style="{ height: gridTreeHeight }" class="box-card">
            <div v-show="showRightMenu">
              <ul id="menu" class="right-menu">
                <li class="menu-item" @click="toClickRightMenu('添加')">
                  <i class="el-icon-plus" style="margin-right: 4px; font-weight: bold" />添加
                </li>
                <li class="menu-item" @click="toClickRightMenu('编辑')">
                  <i class="el-icon-edit" style="margin-right: 4px; font-weight: bold" />编辑
                </li>
                <li class="menu-item" @click="toClickRightMenu('删除')">
                  <i class="el-icon-close" style="margin-right: 4px; font-weight: bold" />删除
                </li>
              </ul>
            </div>

            <el-tree ref="refGridTree" :data="gridTree" node-key="id" :filter-node-method="filterNode"
              :highlight-current="highlightCurrent" :expand-on-click-node="expandOnClickNode"
              :default-expand-all="expandAll" @node-contextmenu="rightClick" @node-click="nodeCick"
              @node-expand="nodeExpand" @node-collapse="nodeCollapse" />
          </div>
        </div>
      </el-card>
    </div>
    <div class="flex flex-sub" style="margin-left: 1rem; width: calc(100% - 390px)">
      <el-card shadow="never" class="box-card flex-sub" style="overflow: auto">
        <div class="div-query">
          <div class="collapse">
            <div class="collapse-header" @click="panelActive = !panelActive">
              <i class="collapse-header-icon" :class="[
                panelActive ? 'el-icon-caret-bottom' : 'el-icon-caret-top',
              ]" />
              {{ panelActive ? '隐藏' : '展开' }}查询条件
            </div>
            <div class="collapse-content">
              <el-collapse-transition>
                <div v-show="panelActive">
                  <el-form size="small" label-position="right">
                    <el-row>
                      <el-col :span="8">
                        <el-form-item label="所属省" label-width="80px">
                          <el-select v-model="searchModel.province" placeholder="请选择所属省" filterable clearable
                            style="width: 100%" @change="getCityList">
                            <el-option v-for="item of provinceList" :key="item.codeId" :label="item.positionName"
                              :value="item.codeId" />
                          </el-select>
                        </el-form-item>
                      </el-col>

                      <el-col :span="8">
                        <el-form-item label="所属市" label-width="80px">
                          <el-select v-model="searchModel.city" placeholder="请选择所属市" filterable clearable
                            style="width: 100%" @change="getCountyList">
                            <el-option v-for="item of cityList" :key="item.codeId" :label="item.positionName"
                              :value="item.codeId" />
                          </el-select>
                        </el-form-item>
                      </el-col>

                      <el-col :span="8">
                        <el-form-item label="所属区县" label-width="80px">
                          <el-select v-model="searchModel.county" placeholder="请选择所属区县" filterable clearable
                            style="width: 100%" @change="onCountyChange">
                            <el-option v-for="item of countyList" :key="item.codeId" :label="item.positionName"
                              :value="item.codeId" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="8">
                        <el-form-item label="网格名称" label-width="80px">
                          <el-input v-model="searchModel.name" placeholder="网格名称" clearable
                            class="filter-item search-item" />
                        </el-form-item>
                      </el-col>

                      <el-col :span="8">
                        <el-form-item label="上级网格" label-width="80px">
                          <treeselect v-model="searchModel.parentGuid" placeholder="选择上级网格" :options="gridTree"
                            :default-expand-level="Infinity" style="width: 100%" @select="onGridSelect">
                            <div slot="value-label" slot-scope="{ node }">
                              {{ node.raw.fullPathText }}
                            </div>
                          </treeselect>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="所属部门" label-width="80px">
                          <treeselect v-model="searchModel.deptGuid" placeholder="选择所属部门" :options="deptTree"
                            :default-expand-level="Infinity" style="width: 100%" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24" style="display: flex;justify-content: center;">
                        <el-form-item style="margin-left: 10px">
                          <el-button type="primary" icon="el-icon-search" @click="toSearch"
                            style="margin-right: 10px">搜素</el-button>
                          <el-button type="info" @click="toReset" style="margin-right: 10px">
                            <i class="el-icon-delete" />
                            重置
                          </el-button>

                          <el-button size="small" @click="getDataList">
                            <i class="el-icon-refresh" style="color: #606266" />
                            <span style="color: #606266">刷新</span>
                          </el-button>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </el-collapse-transition>
            </div>
          </div>
        </div>

        <el-table ref="elTable" v-loading="loading || deleteLoading" border fit size="medium" :data="dataList"
          :row-key="(row) => row.guid" :element-loading-text="deleteLoading ? '删除中,请等待...' : ''"
          @sort-change="onSortChange" @selection-change="onSelectionChange">
          <!-- <af-table-column
            align="center"
            type="selection"
            width="40"
            fixed
            :reserve-selection="true"
          />
          <el-table-column
            align="center"
            type="index"
            width="50"
            fixed
            label="#"
            :index="indexMethod"
          /> -->
          <af-table-column align="center" label="网格名称" prop="name" />
          <!-- <af-table-column
            align="center"
            label="上级网格"
            prop="parentFullPathText"
          /> -->
          <af-table-column align="center" label="网格全路径" prop="fullPathText" />
          <af-table-column align="center" label="网格层级" prop="level" />
          <af-table-column align="center" label="所属部门" prop="deptName" />
          <af-table-column align="center" label="所属省" prop="province" />
          <af-table-column align="center" label="所属地市" prop="city" />
          <af-table-column align="center" label="所属区县" prop="county" />
          <af-table-column align="center" label="排序" prop="orderNum" />

          <af-table-column align="center" label="创建时间" prop="createTime" sortable width="150" />

          <el-table-column align="center" label="操作区" fixed="right" width="120" class-name="small-padding fixed-width">
            <template slot-scope="{ row }">
              <el-tooltip effect="dark" content="详情" placement="top-start">
                <i class="iconfont icon-chakanxiangqing2 i-detail" @click="toDetail(row)" />
              </el-tooltip>

              <i class="iconfont icon-fengefu i-fengefu" />

              <el-tooltip effect="dark" content="编辑" placement="top-start">
                <i class="iconfont icon-bianji2 i-edit" @click="toAdd(row, 'edit')" />
              </el-tooltip>
              <i class="iconfont icon-fengefu i-fengefu" />
              <el-tooltip effect="dark" content="删除" placement="top-start">
                <i class="iconfont icon-shanchu i-delete" @click="toDelete(row, row.name)" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="pagination.pageNum" :limit.sync="pagination.pageSize"
          :page-sizes="pageSizeOptions" @pagination="getDataList" />
      </el-card>
    </div>

    <grid-detail v-if="detailDialogObj.isVisible" ref="detailDialog" :dialog-visible="detailDialogObj.isVisible"
      :title="detailDialogObj.title" :params="params" @close="dialogClose('detailDialogObj')" />

    <grid-add v-if="addDialogObj.isVisible" ref="addDialog" :dialog-visible="addDialogObj.isVisible"
      :title="addDialogObj.title" :params="params" @close="dialogClose('addDialogObj')" @submit="afterSubmit" />
  </div>
</template>

<script>
import dataTableMixins from '@/mixins/data-table-mixins'
import GridManageApi from '@/api/grid-manage'
import Pagination from '@/components/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import GridDetail from './component/Detail'
import GridAdd from './component/Add'

export default {
  name: 'GridList',
  components: {
    Pagination,
    Treeselect,
    GridDetail,
    GridAdd,
  },
  mixins: [dataTableMixins],
  data() {
    return {
      gridTreeHeight: this.getHeightAndWidth(),
      gridTree: [],
      gridName: '',
      expandOnClickNode: false,
      expandAll: false,
      highlightCurrent: true,
      showRightMenu: false,

      provinceList: [],
      cityList: [],
      countyList: [],
      deptTree: [],

      deleteLoading: false,

      selectNodeData: {},
    }
  },
  watch: {
    gridName(val) {
      this.$refs.refGridTree.filter(val)
    },
  },
  mounted() {
    this.getGridTree()

    this.getProvinceList()
    this.getDeptTree()
    this.getDataList()

    // setTimeout(() => {
    //   for (
    //     var i = 0;
    //     i < this.$refs.refGridTree.store._getAllNodes().length;
    //     i++
    //   ) {
    //     // this.$refs.refGridTree.store._getAllNodes()[i].expanded = this.expandAll
    //   }
    // },5*1000)
  },
  methods: {
    getHeightAndWidth() {
      let clientHeight = 0
      if (
        document.body.scrollHeight === window.screen.height &&
        document.body.scrollWidth === window.screen.width
      ) {
        clientHeight = window.screen.height - 5 // 网页可见区域高
      } else {
        clientHeight = document.body.clientHeight - 5 // 网页可见区域高
      }
      return clientHeight - 360 + 'px'
    },

    getGridTree() {
      GridManageApi.getGridTree()
        .then((res) => {
          this.gridTree = res.data.data.rows
        })
        .catch(() => {
          this.gridTree = []
        })
    },
    toSearchGridTree() {
      this.$refs.refGridTree.filter(this.gridName)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    toRefreshGridTree() {
      this.gridName = ''
      this.getGridTree()
    },
    toExpandAll(text) {
      if (text === '是') {
        this.expandAll = true
      } else {
        this.expandAll = false
      }
      for (
        var i = 0;
        i < this.$refs.refGridTree.store._getAllNodes().length;
        i++
      ) {
        this.$refs.refGridTree.store._getAllNodes()[i].expanded = this.expandAll
      }

      // console.log('测试')
      // this.$refs.refGridTree.$children.forEach(
      //   (item) => (item.expanded = this.expandAll)
      // )
    },
    rightClick(event, data, node, obj) {
      this.$refs.refGridTree.setCurrentKey(data.id)

      this.showRightMenu = false // 先把模态框关死，目的是：第二次或者第n次右键鼠标的时候 它默认的是true
      this.showRightMenu = true
      const menu = document.querySelector('#menu')
      menu.style.left = event.clientX - 250 + 'px'
      menu.style.top = event.clientY - 0 + 'px'
      // 给整个document添加监听鼠标事件，点击任何位置执行closeRightMenu方法，及时将菜单关闭
      document.addEventListener('click', this.closeRightMenu)
      console.log('event', event, event.clientX, event.clientY)
      console.log('data', data)
      console.log(node)

      this.selectNodeData = data
      this.searchModel.fullPath = data.fullPath
      this.getDataList()
    },
    closeRightMenu() {
      this.showRightMenu = false
      // 及时关掉鼠标监听事件
      document.removeEventListener('click', this.closeRightMenu)
    },
    nodeCick(data) {
      console.log(data)
      console.log('currentNodeKey=', this.currentNodeKey)
      this.closeRightMenu()

      this.searchModel.fullPath = data.fullPath
      this.getDataList()
      // const list = []
      // list.push(data)
      // this.getDataList(list, '选中')
    },
    nodeExpand(data) {
      this.closeRightMenu()
    },
    nodeCollapse(data) {
      this.closeRightMenu()
    },
    toClickRightMenu(type) {
      if (type === '删除') {
        this.toDelete(this.selectNodeData, this.selectNodeData.label)
      } else if (type === '添加') {
        this.toAdd(this.selectNodeData, 'add')
      } else if (type === '编辑') {
        this.toAdd(this.selectNodeData, 'edit')
      }
    },

    getProvinceList() {
      const data = {
        label: 'level',
        value: 1,
      }
      GridManageApi.getPositionList(data).then((ret) => {
        this.provinceList = ret.data.data
      })
    },
    getCityList(e) {
      if (e == '') {
        this.cityList = []
        delete this.searchModel['province']
        delete this.searchModel['city']
        delete this.searchModel['county']
        delete this.searchModel['zoonId']
        return
      }
      this.cityList = []
      this.countyList = []
      this.searchModel.city = ''
      this.searchModel.county = ''
      const data = {
        label: 'parentCodeId',
        value: this.searchModel.province,
      }
      GridManageApi.getPositionList(data).then((ret) => {
        this.cityList = ret.data.data
      })
    },
    getCountyList() {
      this.countyList = []
      this.searchModel.county = ''
      const data = {
        label: 'parentCodeId',
        value: this.searchModel.city,
      }
      GridManageApi.getPositionList(data).then((ret) => {
        this.countyList = ret.data.data
      })
    },
    onCountyChange(value) {
      this.$set(this.searchModel, this.searchModel.county, value)
    },

    getDeptTree() {
      GridManageApi.getDeptTree().then((ret) => {
        this.deptTree = ret.data.data.rows
        this.deptTree.forEach((ele) => {
          this.getDeptGuidTree(ele)
        })
      })
    },
    getDeptGuidTree(ele) {
      ele.id = ele.guid
      if (ele.children) {
        ele.children.forEach((ele1) => {
          this.getDeptGuidTree(ele1)
        })
      }
    },
    onGridSelect(node, instanceId) {
      console.log('node：', node)
      // this.form.gridMountFullPath = node.fullPath
      // this.form.gridMountFullPathText = node.fullPathText
      //   ? node.fullPathText
      //   : ''
    },

    getDataList() {
      this.loading = true
      const searchModel = this.formatSearchData(this.searchModel)
      GridManageApi.getGridDetailList({
        ...this.pagination,
        ...searchModel,
        ...this.sort,
      })
        .then((ret) => {
          this.dataList = ret.data.data.rows
          this.dataList.forEach((ele) => {
            // this.getParentFullPathText(ele)
            if (ele.parentName && ele.parentName !== '') {
              ele.parentFullPathText = ele.fullPathText.split(
                '>>' + ele.name
              )[0]
            } else {
              ele.parentFullPathText = ''
            }
          })
          this.total = ret.data.data.total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
          this.dataList = []
          this.total = 0
        })
    },

    toSearch() {
      if (this.searchModel.county) {
        this.searchModel.zoonId = this.searchModel.county
      } else if (this.searchModel.city) {
        this.searchModel.zoonId = this.searchModel.city
      } else if (this.searchModel.province) {
        this.searchModel.zoonId = this.searchModel.province
      }
      this.pagination.pageNum = 1
      this.getDataList()
    },
    toReset() {
      this.searchModel = {}
      this.sort = {}
      this.$refs.elTable.clearSort()
      this.$refs.elTable.clearFilter()
      this.toSearch()
    },
    onSortChange(val) {
      console.log(val)
      this.sort.field = val.prop
      this.sort.order = val.order
      this.toSearch()
    },
    onSelectionChange(selection) {
      this.selectedDataList = selection
    },

    toDetail(data) {
      this.params = {
        item: data,
      }
      this.detailDialogObj.title = '网格管理 ＞详情'
      this.detailDialogObj.isVisible = true
    },
    toDelete(data, name) {
      console.log('data=', data)

      this.$confirm(
        '是否确认删除网格名称为"' + name + '"的数据项,及其所有子节点的数据项？',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'btnConfirmStyle',
          cancelButtonClass: 'btnCancelStyle',
        }
      ).then(() => {
        this.deleteLoading = true
        GridManageApi.deleteGrid(data.guid)
          .then((res) => {
            this.deleteLoading = false
            this.$message({
              showClose: true,
              message: '删除成功！',
              type: 'success',
              duration: 4000,
            })
            this.toRefreshGridTree()
            this.toReset()
          })
          .catch(() => {
            this.deleteLoading = false
            this.$message({
              showClose: true,
              message: '删除失败',
              type: 'error',
              duration: 4000,
            })
          })
      })
    },

    toAdd(data, type) {
      this.params = {
        item: data,
        type: type,
      }
      this.addDialogObj.title =
        type === 'edit' ? '网格管理 ＞编辑' : '网格管理 ＞添加'
      this.addDialogObj.isVisible = true
    },
    afterSubmit(operationType) {
      if (operationType === 'add') {
        this.toReset()
        this.toRefreshGridTree()
      } else {
        this.getDataList()
        this.getGridTree()
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import '../../../../styles/part-custom';

.right-menu {
  z-index: 1;
  position: absolute;
  width: 150px;
  position: absolute;
  border-radius: 5px;
  list-style: none;
  background: linear-gradient(rgb(246, 247, 249) 0%, rgb(235, 237, 240) 100%);
  border: 1px solid rgb(217, 214, 196);
  box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 3px 0px;
  color: rgb(31, 31, 31);
  margin: 0px;
  padding: 0px 5px 5px 5px;

  .menu-item {
    margin-top: 5px;
    border-radius: 4px;
    font-size: 14px;
    color: #222222;
    text-align: left;
    padding: 6px 10px;
    cursor: pointer;
    transition: color 0.3s;
  }

  li:hover {
    background-color: #a6a6a6;
    color: #ffffff;
  }
}
</style>
